<template>
  <div>
    <el-row v-show="chapterItem.name" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <h4 style="margin: 12px">{{ chapterItem.name }}</h4>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="text"
          style="font-size: 20px"
          icon="el-icon-edit"
          @click="editChapter(chapterKey,'edit')"
        />
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="text"
          style="font-size: 20px"
          icon="el-icon-delete"
          @click="editChapter(chapterKey,'delete')"
        />
      </el-col>
    </el-row>
    <el-table :data="chapterData.children" border>
      <el-table-column label="序号" type="index" />
      <el-table-column
        v-for="(item,index) in chapterTable.columns"
        :key="index"
        :label="item.label"
        :prop="item.prop"
      >
        <template slot-scope="scope">
          <div v-if="scope.row.is_show === 1">
            <div v-if="item.prop === 'url'">
              <el-progress
                v-if="chapterTable.sel.loading"
                :text-inside="true"
                :stroke-width="15"
                :percentage="chapterTable.sel.percentage"
              />
              <el-upload
                v-else
                :headers="headers"
                class="upload-demo"
                action
                :http-request="httpUpload"
                :show-file-list="false"
              >
                <el-button
                  v-if="!chapterTable.sel.loading"
                  size="small"
                  type="text"
                >{{ chapterTable.sel.url_name? chapterTable.sel.url_name : '点击上传' }}</el-button>
              </el-upload>
            </div>

            <el-input
              v-else-if="item.prop === 'name'"
              v-model="chapterTable.sel[item.prop]"
              placeholder="请输入内容"
            />
          </div>
          <div v-else>
            <el-button
              v-if="item.prop === 'url'"
              type="text"
              @click="preview(scope.row.url)"
            >{{ scope.row.url_name }}</el-button>
            <span v-else-if="item.prop === 'exercises'">
              <router-link
                v-if="scope.row.is_contain_exercise === 1"
                :to="{name:'subject',
                      params: {
                        id:chapterItem.course_id,
                        chapter_id: scope.row.id,
                        link_type: 1,
                      }}"
              >
                <el-button type="text">章节习题</el-button>
              </router-link>
              <el-button v-else type="text" @click="addExercises(scope.row.id)">添加习题</el-button>
            </span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="editRow(scope.row,scope.$index)">编辑</el-button>
          <el-button
            :disabled="scope.row.is_show === 0 || scope.row.is_show === -1"
            type="text"
            @click="saveRow(scope.row,scope.$index)"
          >保存</el-button>
          <el-button type="text" @click="deleteRow(scope.$index,chapterData.children)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="addsonchapter" @click="addSonchapter()">
      <i class="el-icon-plus" />添加子章节
    </div>
    <Exercises :visible="visible" @cancel="cancel" @submitForm="submitForm" />
    <Video :show-video="showVideo" :play-url="playUrl" @handleHideModal="handleHideModal" />
  </div>
</template>

<script>
import { editChapter, delSections, addChapter } from '@/api/admin/sys-course'
import { chooseExercises } from '@/api/admin/sys-question'
import Exercises from '@/components/Exercises'
import Video from '@/components/Video'
import { clients, getNowDate } from '@/utils/index'
export default {
  name: 'Chapter',
  components: {
    Exercises,
    Video
  },
  props: {
    chapterItem: {
      type: Object,
      default: () => {
        return {}
      }
    },
    chapterKey: {
      type: Number,
      default: () => {
        return null
      }
    },
    host: {
      type: String,
      default: () => {
        return ''
      }
    },
    headers: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      chapterTable: {
        sel: null, // 选中行
        columns: [
          {
            prop: 'name',
            label: '子章节名称'
          },
          {
            prop: 'url',
            label: '课件名称'
          },
          {
            prop: 'exercises',
            label: '章节习题'
          }
        ],
        loading: false,
        percentage: 0
      },
      chapterData: {
        children: []
      },
      coursewareUrl: null,
      coursewareName: null,
      visible: false,
      sectionsId: null,
      showVideo: false,
      playUrl: ''
    }
  },
  watch: {
    chapterItem: {
      handler(val) {
        this.chapterData = { ...val }
      }
    }
  },
  created() {
    this.chapterData = { ...this.chapterItem }
  },
  methods: {
    choiceQuestion(event) {
      event.stopPropagation()
    },
    // 新增子章节
    addSonchapter() {
      for (const i of this.chapterData.children) {
        if (i.is_show === 1) return this.$message.warning('请先保存当前编辑项')
      }
      const j = {
        name: '',
        url: '',
        url_name: '',
        exercises: '',
        is_show: 1,
        loading: false,
        percentage: 0
      }
      this.chapterData.children.push(j)
      this.chapterTable.sel = JSON.parse(JSON.stringify(j))
    },
    saveRow(row, index) {
      // 保存
      const data = JSON.parse(JSON.stringify(this.chapterTable.sel))
      for (const k in data) {
        row[k] = data[k] // 将sel里面的value赋值给这一行。ps(for....in..)的妙用，细心的同学发现这里我并没有循环对象row
      }
      if (data.id) {
        editChapter({
          ...data,
          is_show: -1,
          course_id: this.chapterData.course_id
        }).then(response => {
          row.is_show = -1
          this.$emit('say', this.chapterData)
        })
      } else if (this.chapterData.id) {
        const sections = {
          ...this.chapterData.children[index],
          is_show: -1,
          pid: this.chapterData.id,
          course_id: this.chapterData.course_id
        }
        addChapter(sections).then(res => {
          if (res.code === 200) {
            row.is_show = -1
            this.chapterData.children[index].id = res.data
            this.$emit('say', this.chapterData)
          }
        })
      }
    },
    editRow(row) {
      // 编辑
      for (const i of this.chapterData.children) {
        if (i.is_show === 1) return this.$message.warning('请先保存当前编辑项')
      }
      this.chapterTable.sel = row
      row.is_show = 1
      this.$emit('say', this.chapterData)
    },
    deleteRow(index, rows) {
      // 删除
      const deleteData = rows.find((v, i) => i === index)
      if (deleteData.id) {
        this.$confirm('是否确认删除', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            delSections({
              ids: [deleteData.id],
              link_id: deleteData.course_id
            }).then(response => {
              rows.splice(index, 1)
              this.$emit('say', this.chapterData)
            })
          })
          .catch(function() {})
      }
    },
    editChapter(key, type) {
      const payload = {
        chapterItem: this.chapterData,
        chapterKey: key,
        type
      }
      this.$emit('dialogVisible', payload)
    },
    async httpUpload(file) {
      this.$set(this.chapterTable.sel, 'percentage', 0)
      this.$set(this.chapterTable.sel, 'loading', true)
      const client = clients()
      // 判断扩展名
      const tmpcnt = file.file.name.lastIndexOf('.')
      const exname = file.file.name.substring(tmpcnt + 1)
      const imgUrl = 'http://image.twzxjy.com'
      const fileName = `static/uploadfile/${getNowDate()}/${file.file.uid}.${exname}`
      await client.multipartUpload(fileName, file.file, {
        progress: (p, cpt, res) => {
          // 获取分片上传进度、断点和返回值。
          this.$set(
            this.chapterTable.sel,
            'percentage',
            (Math.floor(p * 100) / 100) * 100
          )
          if (p === 1) {
            this.$set(this.chapterTable.sel, 'loading', false)
          }
        },
        parallel: 5, // 并发上传的分片数量
        partSize: 1024 * 1024 * 20,
        // headers,
        // 指定meta参数，自定义Object的元信息。通过head接口可以获取到Object的meta数据。
        meta: {
          year: 2020,
          people: 'test'
        },
        mime: file.type // 上传文件类型
      })
      // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
      const head = await client.head(fileName)
      if (head.status === 200) {
        this.$set(this.chapterTable.sel, 'url', `${imgUrl}/${fileName}`)
        this.$set(this.chapterTable.sel, 'url_name', file.file.name)
      }
    },
    addExercises(id) {
      this.visible = true
      this.sectionsId = id
    },
    cancel() {
      this.visible = false
    },

    submitForm(ids) {
      const parmars = {
        link_id: this.chapterItem.course_id,
        chapter_id: this.sectionsId,
        link_type: 1,
        question_bank_str: ids
      }
      chooseExercises(parmars).then(res => {
        this.visible = false
        const { children } = this.chapterData
        const childrens = children.map(item => {
          if (item.id === this.sectionsId) {
            return { ...item, is_contain_exercise: 1 }
          }
          return item
        })
        this.chapterData = {
          ...this.chapterData,
          children: childrens
        }
      })
    },
    preview(url) {
      this.showVideo = true
      this.playUrl = url
    },
    handleHideModal() {
      this.playUrl = ''
      this.showVideo = false
    }
  }
}
</script>

<style lang="scss" scoped>
.addsonchapter {
  border: 1px solid #c0c4cc;
  text-align: center;
  line-height: 32px;
  cursor: pointer;
  color: #3d64d4;
}
::v-deep .el-loading-spinner {
  top: 90%;
}
</style>
